package org.example.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;

        if("/login".equalsIgnoreCase(req.getRequestURI())) {
            filterChain.doFilter(req, response);
            return;
        }

        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        Object obj = session.getAttribute("username");
        if(null == obj) {
            resp.setHeader("Content-Type", "text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.write("<h1>请登录</h1>");
            writer.flush();
            writer.close();
        }else {
            filterChain.doFilter(req, resp);
        }
    }
}
